
/**
 * Module dependencies.
 */
require.paths.unshift('./mode_modules'); 
var express = require('express');
var markdown = require('github-flavored-markdown').parse;
var path = require('path');
var fs = require('fs');

var app = module.exports = express.createServer();


// Configuration

app.configure(function(){
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  
  // pase form data to key-value paire
  app.use(express.bodyParser());
  // support put and delete HTTP Standar Method
  app.use(express.methodOverride());
  
  app.use(express.static(__dirname + '/public'));
  app.use(app.router);
});

app.configure('development', function(){
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); 
});

app.configure('production', function(){
  app.use(express.errorHandler()); 
});

app.register('.md', {
  compile: function(str, options) {
    var html = markdown(str);
    return function(locals){
      return html.replace(/\{([^}]+)\}/g, function(_, name){
        return locals[name];
      });
    };
  }
});

var config = {
    title: 'NodeBlog',
    author: 'lvjian'
}

// Routes

app.get('/', function(req, res){
  res.render('index', {
    title: config.title + ' - ' + config.author
  });
});

app.get('/blogs/:title.html', function(req, res, next) {
    
    var urlPath = [
        // 获取相对路径, 我的应该是: 
        // /Users/lvjian/projects/nodejs/nodeblog
        process.cwd(),
        '/views/blogs/',
        req.params.title, '.md'
    ].join('');
    
    var filePath = path.normalize(urlPath)
    
    path.exists(filePath, function  (exists) {
        
        if(!exists) {
			console.log('jump 404');  
            next(); 
        } else {
            //res.render(urlPath, {layout: false});
			var content = fs.readFileSync(filePath, config.encoding);  
            //　这里将markdown转成html, 然后以参数形式输出  
            var html_content = markdown(content);  
              
            res.render('blogs/show', {  
                title: config.app + " - Blogs"  
                , blog_content: html_content  
            }); 
        }
    });

})

app.get('*', function(req, res) {
    console.log('404 handler..')
    res.render('404', {
        status: 404,
        title: 'NodeBlog'
    });
})
var config = {
    title: 'E Blog',
    author: 'zhouwt',
    encoding:"UTF-8"
}

app.listen(process.env.VMC_APP_PORT || 3000);  
console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);
